package com.dayaokeji.rhythmschoolstudent.client.main;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.dayaokeji.imkitwrapper.init.ImKitWrapper;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.HomeFragment;
import com.dayaokeji.rhythmschoolstudent.client.message.ConversationsFragment;
import com.dayaokeji.rhythmschoolstudent.client.mine.MineFragment;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.bean.RemoteHostPicker;
import com.dayaokeji.rhythmschoolstudent.event.AppStateEvent;
import com.dayaokeji.rhythmschoolstudent.event.FinishMainEvent;
import com.dayaokeji.rhythmschoolstudent.event.MineEvent;
import com.dayaokeji.rhythmschoolstudent.receiver.VieAnswerReceiver;
import com.dayaokeji.rhythmschoolstudent.service.AppStateService;
import com.dayaokeji.rhythmschoolstudent.service.AppUniqueIdService;
import com.dayaokeji.rhythmschoolstudent.service.MobileInfoCollectService;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ArraysUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ImUtil;
import com.dayaokeji.rhythmschoolstudent.utils.JPushAliasUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionGroup;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.RemoteHostUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private static final String[] FRAGMENT_TAGS = {
            "home", "course", "message", "mine"
    };

    private static final int[] TAB_IDS = {
            R.id.rb_home, R.id.rb_message, R.id.rb_mine
    };

    @BindView(R.id.main_bottom_menu_group)
    RadioGroup mainBottomMenuGroup;
    @BindView(R.id.rb_home)
    RadioButton rbCourse;
    @BindView(R.id.rb_message)
    RadioButton rbMessage;
    @BindView(R.id.rb_mine)
    RadioButton rbMine;

    private Fragment[] fragments;
    private int fragmentIndex = -1;
    private long exitTime;

    private VieAnswerReceiver vieAnswerReceiver = new VieAnswerReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainBottomMenuGroup.setOnCheckedChangeListener(this);
        initFragment(savedInstanceState);
        initIm();
        onNewIntent(getIntent());
        EventBus.getDefault().register(this);
        init();

    }

    private void init() {
        // 只收集一次手机信息
        if (!PrefUtils.isCollectMobileInfo()) {
            startService(new Intent(this, MobileInfoCollectService.class));
        }
        requestReadPhoneStatePermissions();
        ServerCallback.loginNavigation = false;
        saveAppUniqueId();
        startAppStateService();
        UserUtils.checkLogin(this);
        ImKitWrapper.registerVieAnswerBroadcastReceiver(this, vieAnswerReceiver);
        JPushAliasUtils.getInstance().setJPushAlias(App.getAppContext()); // 设置alias
    }

    private void requestReadPhoneStatePermissions() {
        if (!PermissionUtil.hasPermissions(Permission.READ_PHONE_STATE)) {
            PermissionUtil.Build build = new PermissionUtil.Build();
            build.setTips("请允许我们获取存储权限，以提供更好的服务");
            build.setPermissions(new String[]{Permission.READ_PHONE_STATE});
            addDisposable(PermissionUtil.checkPermission(this,build).subscribe(permissionResult -> {
                if (!permissionResult.isHasAccess()) {
                    Snackbar.make(getWindow().getDecorView(), "您拒绝了我们部分权限，有些功能将受到影响",  Snackbar.LENGTH_LONG).show();
                }
            }));
        }
    }

    private void saveAppUniqueId() {
        if (PermissionUtil.hasPermission(PermissionGroup.STORE)) {
            startService(new Intent(MainActivity.this, AppUniqueIdService.class));
        }else{
            addDisposable(PermissionUtil.checkStorePermission(this, "请允许我们获取存储权限，以提供更好的服务").subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean){
                        startService(new Intent(MainActivity.this, AppUniqueIdService.class));
                    }else{
                        Snackbar.make(getWindow().getDecorView(), "您拒绝了我们部分权限，有些功能将受到影响",  Snackbar.LENGTH_LONG).show();
                    }
                }
            }));
        }
    }

    /**
     * 初始化im配置
     */
    private void initIm() {
        RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
        if (currentRemoteHost != null) {
            UserInfo userInfo = UserUtils.getUserInfo();
            if (userInfo != null) {
                String uid = currentRemoteHost.getId() + "-" + userInfo.getId();
                Logger.d("main uid === "+uid);
                ImKitWrapper.init(this,uid);
            }
            // change imgae url
            ApiConstantKt.setRemoteImageUrl(currentRemoteHost.getHost()+"/course/resource/download?resourceId=");
            Logger.d("image base url === "+currentRemoteHost.getHost()+"/course/resource/download?resourceId=");
            final String host = currentRemoteHost.getHost();
            if (!TextUtils.isEmpty(host)) {
                String imHost = ImUtil.imHost(host);
                loginIm(imHost, host);
            }
        }
    }

    private void loginIm(final String host, final String apiUrl) {
        if (!TextUtils.isEmpty(UserUtils.getCurrentUserName())) {
            //
            ImKitWrapper.setHeaderToken(UserUtils.getAccessToken());
            ImUtil.getImToken(UserUtils.getCurrentUid(), UserUtils.getCurrentUserName(), token -> ImKitWrapper.login(App.getAppContext(), UserUtils.getCurrentUid(), token,host,apiUrl));
        }
    }



    /**
     * 初始化主页全部Fragment
     *
     * @param savedInstanceState
     */
    private void initFragment(Bundle savedInstanceState) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        int index = 0;
        if (savedInstanceState == null) {
            fragments = new Fragment[]{
                    new HomeFragment(),  new ConversationsFragment(), new MineFragment()
            };
            int fragmentsSize = fragments.length;
            for (int i = 0; i < fragmentsSize; i++) {
                fragmentTransaction.add(R.id.content, fragments[i], FRAGMENT_TAGS[i]);
            }
        } else {
            fragments = new Fragment[FRAGMENT_TAGS.length];
            int fragmentTagsSize = FRAGMENT_TAGS.length;
            for (int i = 0; i < fragmentTagsSize; i++) {
                fragments[i] = supportFragmentManager.findFragmentByTag(FRAGMENT_TAGS[i]);
            }

            index = savedInstanceState.getInt("fragmentIndex", 0);
        }

        for (Fragment fragment : fragments) {
            if (fragment != null) {
                fragmentTransaction.hide(fragment);
            }
        }
        fragmentTransaction.commit();
        mainBottomMenuGroup.check(TAB_IDS[index]);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            String action = intent.getAction();
            if ("message".equals(action)) {
                mainBottomMenuGroup.check(R.id.rb_message);
            }
        }
    }

    /**
     * fragment切换
     * @param radioGroup
     * @param checkId
     */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
        UserUtils.checkLogin(this);
        int tabIndex = ArraysUtils.findArrayIndex(TAB_IDS, checkId);
        if (tabIndex != fragmentIndex && tabIndex != -1) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            if (fragmentIndex >= 0) {
                fragmentTransaction.hide(fragments[fragmentIndex]);
            }
            Fragment fragment = fragments[tabIndex];
            if (fragment != null) {
                Toolbar toolbar = ((MainFragment) fragment).getToolbar();
                setSupportActionBar(toolbar);
                fragmentTransaction.show(fragment);
            }
            fragmentIndex = tabIndex;
            fragmentTransaction.commitAllowingStateLoss();
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("fragmentIndex", fragmentIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().post(new AppStateEvent(true, Constant.APP_STATE_FOREGROUND_CODE));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void switchMine(MineEvent mineEvent) {
        mainBottomMenuGroup.check(R.id.rb_mine);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void finishMain(FinishMainEvent finishMainEvent) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new AppStateEvent(false, Constant.APP_STATE_EXIT_CODE));
        EventBus.getDefault().unregister(this);
        UserUtils.stopService(this);
        ImKitWrapper.unRegisterVieAnswerBroadcastReceiver(this, vieAnswerReceiver);
        super.onDestroy();
    }

    private void startAppStateService() {
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(MainActivity.this, AppStateService.class));
            }else{
                startService(new Intent(MainActivity.this, AppStateService.class));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onBackPressed() {
        exitApp();
    }

    private void exitApp() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.info("再按一次后退键退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            EventBus.getDefault().post(new AppStateEvent(false, Constant.APP_STATE_EXIT_CODE));
            EventBus.getDefault().unregister(this);
            UserUtils.stopService(this);
            ImKitWrapper.unRegisterVieAnswerBroadcastReceiver(this, vieAnswerReceiver);
            ActivityStackManager.finish();
            AndroidUtils.exitApp();
        }
    }
}
